var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
if(!config){
	config = parent.parent.parent.CONFIG;
	system = parent.parent.parent.SYSTEM;
}
var api = frameElement.api, W = api.opener;

//左侧查询所有商品url
var queryurl = config.BASEPATH+'shop/gift/page_product';
var detailurl = config.BASEPATH+"shop/gift/temp_loadproduct";
var saveUrl = config.BASEPATH+'shop/gift/temp_save';

$.fn.subtext=function(value,count,txt){	
	if (value.length>count){
		if (txt==null){txt='..'}
		$(this).text(value.substring(0,count)+txt);
		$(this).attr('title',value); 
	}else{
		$(this).text(value);
	}    
};    

$.fn.subval=function(value,count){	
	if (value.length>count){
		$(this).val(value.substring(0,count));
		$(this).attr('title',value); 
	}else{
		$(this).val(value);
	}    
};

var Utils = {
	formatImgCount:function(value){
    	if(parseInt(value)>0){
    		return "有";
    	}
    	return "无";
    },
    operFmatter:function(val, opt, row){
    	var html_con = '<div class="operating" data-id="' + row.id + '">';
    	html_con += '<span class="iconfont i-hand" onClick="javascript:handle.addImage(\''+row.pd_code+'\');" title="图片上传">&#xe654;</span>';
    	html_con += '</div>';
    	return html_con;
    }
};

var handle = {
	addImage: function(pd_code){//新增图片
		if(pd_code != undefined && pd_code != ''){
			$.dialog({ 
				id: 'id',
				title: '商品图片',
				max: false,
				min: false,
				width: '830px',
				height: '400px',
				fixed:false,
				drag: true,
				content:'url:'+config.BASEPATH+'base/product/to_img_add?pd_code='+pd_code
			});
		}else{
			Public.tips({type: 1, content : '数据出错，请联系管理员!!!'});
		}
    },
	input:function(id,pd_code){
		THISPAGE.loadDetailGrid(id,pd_code);
	},
	next:function(){
		var currentId = $("#currentId").val();
		var currentPdCode = $("#currentPdCode").val();
		var selectedIds = $("#grid").jqGrid('getGridParam', 'selarrrow');
	    if (selectedIds!=null){
			var selectedId;
			for(var i=0;i<selectedIds.length;i++){
				selectedId=selectedIds[i];
				if(selectedId != currentId){
					continue;
				}
				var nextId = selectedIds[(i+1)%selectedIds.length];
				var rowData = $('#grid').jqGrid('getRowData', nextId);
				THISPAGE.loadDetailGrid(nextId,rowData.pd_code);
				return;
			}
		}
	},
	save:function(next){
		var jsonObject=updateDatas.get();
		var jsonString=JSON.stringify(updateDatas.get());
		if (jsonObject.length>0){
			var pd_code = $("#currentPdCode").val();
			$('#btnSave').attr('disabled','disabled');
			$('#btnSaveAndNext').attr('disabled','disabled');
			$.ajax({
				type:"POST",
				url:saveUrl,
				data:{data:Public.encodeURI(jsonString),pd_code:pd_code},
				async:true,
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						updateDatas.clear();
						Public.tips({type: 3, content : '保存成功！'});
						if(next==1){
							handle.next();
						}else{
							$("#txtSearch").focus().select();;
						}
						W.isRefresh=true;
					}else{
						Public.tips({type: 1, content : '保存失败！'});
					}
					$('#btnSave').removeAttr('disabled');
					$('#btnSaveAndNext').removeAttr('disabled');
				}
			});
		}else{
			if(next==1){
				handle.next();
			}else{
				$("#txtSearch").focus();
			}
		}
	}
};
var chkVaildateStock,chkRealStock,chkUseableStock;
var columnsOriginal = null;
var dataValueOriginal = null;

var THISPAGE = {
	init:function (data){
		this.$_txtSearch = $('#txtSearch');
		if($("#txtSearchHidden").val() != ''){
			$('#txtSearch').val($("#txtSearchHidden").val());
		}
		this.$_exactQuery = $('#exactQuery');
		this.$_exactQuery = $("#exactQuery").cssCheckbox();
		chkVaildateStock=$("#chkVaildateStock").cssCheckbox();
		chkRealStock=$("#chkRealStock").cssCheckbox();
		chkUseableStock=$("#chkUseableStock").cssCheckbox();
		$("#chkUseableStock").css('display','none');
		$("#chkVaildateStock").css('display','none');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		if(realStock && useableStock){
			$('#spanDescribe').text('注:实际库存/可用库存/录入数量');
		}else if(realStock){
			$('#spanDescribe').text('注:实际库存/录入数量');
		}else if(useableStock){
			$('#spanDescribe').text('注:可用库存/录入数量');
		}else{
			$('#spanDescribe').text('注:录入数量');
		}
		this.initGrid();
		this.addEvent();
	},
	initDom: function(data){
		var _self = this;
		this.$sizeDetailGrid=$('#sizeDetail');
		this.selectCell={iRow:0,iCol:0,rowid:0,value:''};
		$('#txtNo').text(product.no);
		$('#txtName').text(product.name);
		$('#txtTpName').text(product.tp_name);
		$('#txtBdName').text(product.bd_name);
		$('#txtSSName').text(product.season);
		$('#txtYear').text(product.year);
		$('#txtUnitPrice').text(product.sell_price);
		$('#txtUnitPriceShow').val(PriceLimit.formatBySell(product.sell_priceShow));
		$('#txtSortPrice').text(product.sort_price);
		$('#txtSortPriceShow').val(PriceLimit.formatByDistribute(product.sort_priceShow));
		if(product.img_path != null && product.img_path != ''){
			$("#ProductPhoto").attr("src",$("#ftpURL").val()+product.img_path);
		}else{
			$("#ProductPhoto").attr("src",config.BASEPATH+'resources/grid/images/nophoto.png');  
		}
	},
	setCellSelected:function(allotAmount){
		var selectCell=this.selectCell;
		var value=$('#grid').getCell(selectCell.iRow,selectCell.iCol);
		var arrValue=value.split('/');
		if (allotAmount!=''){
			if (arrValue[0]==''){
				arrValue[0]='0';
			}
			arrValue[0]+='/'+allotAmount;
		}
		this.$grid.setCell(selectCell.iRow,selectCell.iCol,arrValue[0]);
	},
	buildUrlParams:function(){
		var _self = this;
		var searchContent = _self.$_txtSearch.val() === '请输入关键字查询' ? '' : _self.$_txtSearch.val();
		var exactQuery = _self.$_exactQuery.chkVal().join() ? 1 : 0;
		var params="searchContent="+Public.encodeURI(searchContent);
		params += "&exactQuery="+exactQuery;
		if(api.data.gil_shop_code != undefined){
			params += "&gil_shop_code="+api.data.gil_shop_code;
		}
		return params;
	},
	buildDetailUrlParams:function(pd_code){
		var params="pd_code="+pd_code;
		if(api.data.gil_shop_code != undefined){
			params += "&gil_shop_code="+api.data.gil_shop_code;
		}
		return params;
	},
	initGrid:function (){
		var gridWH = Public.setGrid();
		var colModel = [
		    {label:'操作',name: 'operate', width: 40, fixed:true, formatter:Utils.operFmatter, title: false,sortable:false},
		    {label:'商品编号',name: 'pd_code', index: 'pd_code',width: 80, fixed:true,hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no',width: 80, fixed:true, align: 'left'},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 90, fixed:true ,title: true, align: 'left'},
	    	{label:'库存',name: 'sd_amount', index: 'sd_amount', width: 40, fixed:true ,title: true, align: 'right'},
	    	{label:'图片',name: 'img_count', index: 'img_count', width: 40, title: false,formatter:Utils.formatImgCount},
	    	{label:'录入',name: 'state',index:'',width: 60,align:'center', title: false},
	    ];
	    $("#grid").jqGrid({
	    	url:queryurl+"?"+THISPAGE.buildUrlParams(),
	        datatype: 'json',
	        height: gridWH.h-120,
	        width:435,
	        altRows:true,
	        //data:items,//加载页面json数据
	        colModel: colModel,
	        rownumbers:true,
	        multiselect:true,//多选
	        rowNum:30,//每页条数
			rowList:config.BASEROWLIST,//分页条数
	        gridview:true,//false构造一行数据后添加到grid中
	        pager: '#page',
	        shrinkToFit:false,//ture，则按比例初始化列宽度
	        forceFit:false,//调整列宽度会改变表格的宽度  shrinkToFit 为false时，此属性会被忽略
	        viewrecords: true,//是否要显示总记录数信息
            pgbuttons:true,
            cellEdit: true,
            scroll: 1,
            recordtext:'{0} - {1} 共 {2} 条',
            jsonReader: {
            	root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
				repeatitems : false,
				id: 'pd_id'  //图标ID
			},
			loadComplete: function(data){
				var grid=$("#grid");
				var ids = grid.jqGrid('getDataIDs');
				for(var i=0;i < ids.length;i++){
					var rowData = grid.jqGrid("getRowData", ids[i]);
					var btnHtml='<input type="button" value="录入" class="btn_xg"'+' onclick="javascript:handle.input('+ids[i]+',\''+rowData.pd_code+'\');" />';
					grid.jqGrid('setRowData',ids[i],{state:btnHtml});
				}
				if(ids.length == 1){//输入货号点击回车进入页面
					var rowData = grid.jqGrid("getRowData", ids[0]);
					handle.input(ids[0],rowData.pd_code);
				}else if(ids.length > 1){
					$("#grid").editCell(1,2);
//					$("#grid").setSelection(ids[0]);
				}
//				Public.resizeSpecifyGrid("grid",110,680);
			},
			loadError : function(xhr,st,err) {
			},
	        ondblClickRow:function(rowid,iRow,iCol,e){
	        },
	        onCellSelect:function(rowid,iCol, cellcontent,e){
	        },
	        onSelectCell:function(rowid,cellname,value,iRow,iCol){
	        	var event = window.event||arguments[0];
				if(event.keyCode === 13){
					var rowData = $("#grid").jqGrid("getRowData", rowid);
					handle.input(rowid,rowData.pd_code);
				}
	        }
	    });
	},
	loadDetailGrid:function(id,pd_code){
		var curRowData = $("#grid").jqGrid("getRowData", id);
		if(curRowData.img_count == '0' || curRowData.img_count == '无'){
			Public.tips({type: 2, content : '当前货号没有图片，请上传图片！'});
			return;
		}
		$("#currentId").val(id);
		$("#currentPdCode").val(pd_code);
		var grid=$("#grid");
		var ids = $("#grid").jqGrid('getDataIDs');
		for(var i=0;i < ids.length;i++){
			var rowData = grid.jqGrid("getRowData", ids[i]);
			if(id == ids[i]){
				$("#grid").jqGrid('setRowData', ids[i], false, { color: 'blue' });
			}else{
				$("#grid").jqGrid('setRowData', ids[i], false, { color: '#696969' });
			}
		}
		$("#btnSave").css('display','');
    	$("#btnExit").css('display','');
    	$("#ProductInfo").css('display','');
    	var selectedIds = $("#grid").jqGrid('getGridParam', 'selarrrow');
	    if (selectedIds == null || selectedIds.length <= 1){
	    	$("#btnSaveAndNext").css('display','none');
	    }else{
	    	$("#btnSaveAndNext").css('display','');
	    }
		$.ajax({
			type:"POST",
			url:detailurl+'?'+THISPAGE.buildDetailUrlParams(pd_code),
			cache:false,
			dataType:"json",
			success:function(dataValue){
				if(dataValue != ""){
					product=dataValue.product;
					$('#sizeDetail').GridUnload();
					THISPAGE.initDom();
					THISPAGE.initDetailGrid(dataValue.sizes,dataValue.data);	
				}
			}
		});
	},
	initDetailGrid:function(columns,dataValue){
		$("#priceModifyed").val('')
		updateDatas.clear();//清空json中临时数据
		columnsOriginal = columns;
		dataValueOriginal = dataValue;
		var grid=this.$sizeDetailGrid;
		var _self=this;
		var gridWH = Public.setGrid();
		var colModel = [
	    	{label:'颜色', name: 'cr_name',index: '', width: 70,fixed:true},
	    	{name:'cr_code',hidden:true},
	    	{label:'杯型', name: 'br_name',index: '', width: 40,fixed:true,align:'center'},
	    	{name:'br_code',hidden:true},
	    	{name:'id',hidden:true}
	    ];
		if (columns!=null&&columns.length>0){
			for ( var i = 0; i < columns.length; i++) {
				colModel.push({name: columns[i].code
					,label:columns[i].name
					, index: columns[i].code
					, width: 60
					,editable:true 
				});
			}	
		}
		colModel.push({label:'小计',name:'totalAmount', width: 60});
		grid.jqGrid({
			datatype: 'json',
			autowidth: true,
			height: gridWH.h-100,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			viewrecords: true,
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			shrinkToFit:false,
            cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
            userDataOnFooter: true,
            triggerAdd:false,
			jsonReader: {
				root: 'rows',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){
			},
			formatCellTitle:function(val,iRow, iCol){
				var key= colModel[iCol-1].name;
				var value = dataValueOriginal.rows[iRow-1][key];
				value = $.trim(value);
				if(value == ''){
					return '';
				}
				var arrValue=value.split('/');
				if(arrValue !=null && arrValue != '' && arrValue.length > 0){
					return "实际："+arrValue[0];
				}else{
					return '';
				}
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){//切换输入框前处理
				var value=grid.getCell(iRow,iCol);
				var selectCell=_self.selectCell;
				selectCell.rowid=rowid;
				selectCell.iRow=iRow;
				selectCell.iCol=iCol;
				selectCell.value=value;
				var arrValue=value.split('/');
				var inputValue;
				
				var realStock = chkRealStock.chkVal().join() ? true : false;
				var useableStock = chkUseableStock.chkVal().join() ? true : false;
				if(realStock && useableStock){
					if (arrValue!=''){
						selectCell.value0=arrValue[0];
						selectCell.value1=arrValue[1];
						selectCell.value2=arrValue[2];
					}else{
						selectCell.value0=0;
						selectCell.value1=0;
						selectCell.value2='';
					}	
					inputValue=selectCell.value2;
				}else if(realStock || useableStock){
					if (arrValue!=''){
						selectCell.value0=arrValue[0];
						selectCell.value1=arrValue[1];
					}else{
						selectCell.value0=0;
						selectCell.value1='';
					}
					inputValue=selectCell.value1;
				}else{
					selectCell.value0=arrValue[0];
					inputValue=selectCell.value0;
				}
				return inputValue;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				var selectCell=_self.selectCell;
				if (Validate.amount(value)){
					//验证库存
					var vaildateStock=chkVaildateStock.chkVal().join() ? true : false;
					var realStock = chkRealStock.chkVal().join() ? true : false;
					var useableStock = chkUseableStock.chkVal().join() ? true : false;
					if(vaildateStock){
						
						var originalValue = dataValueOriginal.rows[iRow-1][colModel[iCol-1].name];//从原始数据中取得实际库存的值
						originalValue = $.trim(originalValue);
						var stockAmount = 0;
						var arrValue=originalValue.split('/');
						if(arrValue != null && arrValue != '' && arrValue.length > 0){
							stockAmount = arrValue[0];
						}
						if(parseInt(value)>parseInt(stockAmount)){
							Public.tips({type: 2, content : '库存不足！'});
							if(realStock && useableStock){
								value = _self.selectCell.value2;
							}else if(realStock || useableStock){
								value = _self.selectCell.value1;
							}else{
								value = _self.selectCell.value0;
							}
						}
					}
					value=value==0?'':value;
					
					var realStock = chkRealStock.chkVal().join() ? true : false;
					var row=grid.getRowData(rowid);
					var unitPrice = $("#txtUnitPriceShow").val();
					if(isNaN(unitPrice)){
						unitPrice = product.sell_price;
					}
					var sortPrice = $("#txtSortPriceShow").val();
					if(isNaN(sortPrice)){
						sortPrice = product.sort_price;
					}
					var updateData={
						no:product.no
//						,unit_name:product.unit_name
						,cost_price:product.cost_price
						,unitPrice:unitPrice
						,sortPrice:sortPrice
						,sell_price:product.sell_price
						,szg_code:product.szg_code
						,cr_code:row.cr_code
						,sz_code:colModel[iCol-1].name
						,br_code:row.br_code
						,backStockAmount:selectCell.value0
						,amount:value==''?0:value
					};
					
					var newValue;
					if(realStock && useableStock){
						updateData.initAmount=selectCell.value2==''?0:selectCell.value2;
						if (selectCell.value0!=0
								||selectCell.value1!=0||value!=''){
							newValue=selectCell.value0+'/'+selectCell.value1+'/'+value;	
						}else{
							newValue='';
						}
					}else if(realStock || useableStock){
						updateData.initAmount=selectCell.value1==''?0:selectCell.value1;
						if (selectCell.value0!=0||value!=''){
							newValue=selectCell.value0+'/'+value;	
						}else{
							newValue='';
						}
					}else{
						updateData.initAmount=selectCell.value0==''?0:selectCell.value0;
						newValue = value;
					}
					updateDatas.add(updateData);
					return newValue;
				}else{ 
					return _self.selectCell.value;
				}
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				THISPAGE.gridTotal();
				var maxRow = dataValue.rows.length;
				var maxCol = columns.length+5;
				var event = window.event||arguments[0];
				if(event.keyCode === 13 && ((iRow === maxRow && iCol === maxCol) || event.ctrlKey)){
					if($("#btnSaveAndNext").css('display') != 'none'){
						$('#btnSaveAndNext').click();
					}else{
						$('#btnSave').click();
					}
				}
			},
			plusKeyDown:function(){
				if($("#btnSaveAndNext").css('display') != 'none'){
					$('#btnSaveAndNext').click();
				}else{
					$('#btnSave').click();
				}
			}
	    });
		$('#sizeDetail').clearGridData();
		if (dataValue!=null){		
			var isBraSize=false;
			var grid=$('#sizeDetail');
			for(var i=0;i< dataValue.rows.length;i++){
				grid.jqGrid('addRowData', i + 1, dataValue.rows[i]);
				if (!isBraSize&&dataValue.rows[i].br_code!=''){
					isBraSize=true;
				}
			}
			if (isBraSize) {
				grid.showCol("br_name");
            }else{
            	grid.hideCol("br_name");
            }
	    	Public.resizeSpecifyGrid("sizeDetail",125,515);
	    	THISPAGE.reloadDetailGridData();
	    	/*grid.jqGrid("nextCell",1,1);//第一个输入框聚焦*/	    	
		}
	},
	reloadDetailGridData:function(){
		var grid=$('#sizeDetail')
		,rows=grid.getRowData()
		,colModel=grid.getGridParam('colModel');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue = null;
				var originalValue = null;
				if(row[key] != null && row[key] != ''){
					arrValue=row[key].split('/');
				}
				if(dataValueOriginal.rows[rowIndex][key] != null && dataValueOriginal.rows[rowIndex][key] != ''){
					originalValue = dataValueOriginal.rows[rowIndex][key].split('/');
				}
				var newValue = '';
				
				if(originalValue != null && originalValue != '' && originalValue.length > 0){
					if(originalValue[0] != null && originalValue[0] != '' && realStock){
						newValue += originalValue[0]+'/';
					}					
					if(originalValue[1] != null && originalValue[1] != '' && useableStock){
						newValue += originalValue[1]+'/';	
					}
				}else{
					if(realStock){
						newValue += '0/';
					}
					if(useableStock){
						newValue += '0/';
					}
				}
				
				if (arrValue != null && arrValue != '' && arrValue.length > 0){
					newValue += arrValue[arrValue.length-1]
				}
				rows[rowIndex][key] = newValue;
			}
		}
		grid.clearGridData();
		for(var i=0;i< rows.length;i++){
			grid.jqGrid('addRowData', i + 1, rows[i]);
		}
		THISPAGE.gridTotal();
	},
	gridTotal:function(iRow,iCol){
		
		var grid=$('#sizeDetail')
			,rows=grid.getRowData()
			,rowFoot=grid.footerData()
			,colModel=grid.getGridParam('colModel');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var total1=0,total2=0,total3=0;
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if(arrValue[0] != null && arrValue[0]!='' && !isNaN(arrValue[0])){
						total1+=parseInt(arrValue[0]);	
					}					
					if(arrValue[1] != null && arrValue[1]!='' && !isNaN(arrValue[1])){ 
						total2+=parseInt(arrValue[1]);
					}
					if(arrValue[2] != null && arrValue[2]!='' && !isNaN(arrValue[2])){
						total3+=parseInt(arrValue[2]);	
					}
				}
			}
			
			if(realStock && useableStock){
				grid.setCell(row.id,'totalAmount',(total1+'/'+total2+'/'+total3));
			}else if(realStock || useableStock){
				grid.setCell(row.id,'totalAmount',(total1+'/'+total2));
			}else{
				grid.setCell(row.id,'totalAmount',(total1));
			}
		}
		rows=grid.getRowData();
		for ( var colIndex = 6; colIndex < colModel.length; colIndex++) {
			var total1=0,total2=0,total3=0;
			var key= colModel[colIndex].name;
			for ( var index = 0; index < rows.length; index++) {
	    		var row=rows[index];
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if(arrValue[0] != null && arrValue[0]!='' && !isNaN(arrValue[0])){
						total1+=parseInt(arrValue[0]);	
					}					
					if(arrValue[1] != null && arrValue[1]!='' && !isNaN(arrValue[1])){ 
						total2+=parseInt(arrValue[1]);
					}
					if(arrValue[2] != null && arrValue[2]!='' && !isNaN(arrValue[2])){
						total3+=parseInt(arrValue[2]);	
					}
				}
			}
			if(realStock && useableStock){
				if (total1==0&&total2==0&&total3==0){
					json= '{"'+colModel[colIndex].name+'":""}';
				}else{
					json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2+'/'+total3)+'"}';
				}	
			}else if(realStock || useableStock){
				if (total1==0&&total2==0){
					json= '{"'+colModel[colIndex].name+'":""}';
				}else{
					json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2)+'"}';
				}
			}else{
				json= '{"'+colModel[colIndex].name+'":"'+(total1)+'"}';
			}
			var jj=eval('('+json+')');
			grid.footerData("set",jj);
		}
		grid.footerData("set",{colorName:'合计：'});
	},
	reloadData:function(data){
		$("#grid").jqGrid('setGridParam',{datatype:"json",url:queryurl+"?"+THISPAGE.buildUrlParams()}).trigger("reloadGrid");
	},
	initTip:function(){
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		if(realStock && useableStock){
			$('#spanDescribe').text('注:实际库存/可用库存/录入数量');
		}else if(realStock){
			$('#spanDescribe').text('注:实际库存/录入数量');
		}else if(useableStock){
			$('#spanDescribe').text('注:可用库存/录入数量');
		}else{
			$('#spanDescribe').text('注:录入数量');
		}
	},
	addEvent:function(){
		var _self = this;
		$(window).resize(function(){
			Public.resizeSpecifyGrid("grid",110,680);
		});
		//实际库存点击
		$('#chkRealStock').click(function(){
			THISPAGE.initTip();
			THISPAGE.reloadDetailGridData();
		});
		//可用库存点击
		$('#chkUseableStock').click(function(){
			THISPAGE.initTip();
			THISPAGE.reloadDetailGridData();
		});
		$('#search').click(function(){
			THISPAGE.reloadData();
		});
		//保存
		$('#btnSave').on('click', function(e){
			handle.save();
		});
		//保存并下一条
		$('#btnSaveAndNext').on('click', function(e){
			handle.save(1);
		});
		//保存并下一条
		$('#btnExit').on('click', function(e){
			api.close();
		});
	}
};

var updateDatas={
	datas:[]
	,add:function(updateData){
		var isExists=false;
		for ( var i = 0; i < this.datas.length; i++) {
			var data=this.datas[i];
			if (data.no==updateData.no
				&&data.cr_code==updateData.cr_code
				&&data.sz_code==updateData.sz_code
				&&data.br_code==updateData.br_code
				){
				data.amount=updateData.amount;
				isExists=true;
				break;
			}
		}
		if (!isExists){
			this.datas.push(updateData);
		}
	},
	get:function(){
		var datas=this.datas;
		var data;
		//去除没有更改的数据
		for ( var i = 0; i < datas.length; i++) {
			data=datas[i];
			if (data.initAmount==='' || (data.initAmount === 0 && data.amount != 0)){
				data.operateType='add';
			}else if (data.initAmount==data.amount){
				datas.splice(i,1);
				i--;
			}else{
				data.operateType='update';
			}
		}
		if (datas.length>0){
			$.isRefresh=true;
		}
		return datas;
	},
	clear:function(){
		this.datas = [];
	}
};

var Validate={
	amount:function(value){
		var reg=/^[0-9]*[0-9][0-9]*$/;
		return reg.test(value);
	}
};
THISPAGE.init();